package com.cn.qgx428.lazydiary.Presenter

import android.util.Log
import com.cn.qgx428.lazydiary.Utils.MD5Utils
import com.cn.qgx428.lazydiary.Utils.SPUtil
import com.cn.qgx428.lazydiary.db.bean.CBill
import com.cn.qgx428.lazydiary.db.dao.BillDao
import com.cn.qgx428.lazydiary.extension.getCurrenMouthWidthYear
import com.cn.qgx428.lazydiary.extension.getCurrenTimePrecise
import com.cn.qgx428.lazydiary.network.NetworkManager
import com.cn.qgx428.lazydiary.network.bean.Bill
import com.cn.qgx428.lazydiary.network.bean.BillResponse
import com.cn.qgx428.lazydiary.network.bean.CommonResponse
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*

/**
 * Created by qinguanxiong on 2018/2/26.
 */
class BillPresenter {
    companion object {
        /**
         * 添加账单到本地
         */
        fun addBill(type: String, specific: String, price : String, no: String, remark: String, f:()-> Unit){
            val bill = CBill()
            bill.price = price
            bill.no = no
            bill.type = type
            bill.total = ( no.toFloat() * price.toFloat() ).toString()
            bill.specific = specific
            bill.remark = remark
            bill.createTime = Calendar.getInstance().getCurrenTimePrecise()
            bill.md5 = MD5Utils.encrypt(bill.createTime)
            val dao = BillDao()
            val id = dao.add(bill)
            f()
        }

        /**
         * 同步账单到网络
         */
        fun syncUp(listener: () -> Unit){
            val lock = Any()
            val dao = BillDao()
            val bills = dao.getAll()
            if (bills != null && bills.size > 0) {
                var ready = 0
                bills.forEach {
                    NetworkManager.getInstance()
                            .getBillService()
                            .update(it.createTime, it.type!!, it.specific, it.price!!,
                                    it.no!!, it.total!!, it.remark!!, SPUtil.currntUserId().toInt())
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(object : Observer<CommonResponse>{
                                override fun onError(e: Throwable?) {
                                    Log.d("billPresenter", e!!.message)
                                }

                                override fun onNext(t: CommonResponse?) {
                                    synchronized(lock){
                                        ready ++;
                                        if (ready == bills.size){
                                            syncLoad(listener)
                                        }
                                    }
                                }

                                override fun onCompleted() {
                                }
                            })
                }
            }
            // 本地无数据，直接从网络拉取
            else{
                syncLoad(listener)
            }
        }

        /**
         * 从网络拉取
         */
        fun syncLoad(listener: () -> Unit){
            NetworkManager.getInstance()
                    .getBillService()
                    .get(SPUtil.currntUserId().toInt())
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<BillResponse>{
                        override fun onError(e: Throwable?) {
                            Log.d("billPresenter", "get() : " + e!!.message)
                        }

                        override fun onNext(t: BillResponse?) {
                            val bills = t?.bills
                            var cBills: MutableList<CBill> = mutableListOf()
                            val dao = BillDao()
                            bills?.forEach {
                                // 有更新，无插入
                                cBills = dao.queryByColum("createTime", it.createtime) as MutableList<CBill>
                                if (cBills.size != 0){

                                } else{
                                    val bill = CBill()
                                    bill.createTime = it.createtime
                                    bill.no = it.no
                                    bill.price = it.price
                                    bill.total = it.total
                                    bill.specific = it.specific
                                    bill.type = it.type
                                    bill.remark = it.remark
                                    dao.add(bill)
                                }
                            }
                            listener()
                        }


                        override fun onCompleted() {

                        }
                    })
        }
    }
}